<template>
  <div id="app">
    <h1>在线生成图像</h1>

    <div>
      <label for="width">宽度:</label>
      <input id="width" v-model.number="width" type="number" min="1" />

      <label for="height">高度:</label>
      <input id="height" v-model.number="height" type="number" min="1" />

      <label for="format">格式:</label>
      <select id="format" v-model="format">
        <option value="image/png">PNG</option>
        <option value="image/jpeg">JPEG</option>
      </select>

      <button @click="generateImage" :disabled="loading">
        {{ loading ? '生成中...' : '生成图像' }}
      </button>
    </div>

    <div v-if="imageURL">
      <h2>预览图像:</h2>
      <img
        :src="imageURL"
        alt="Image Preview"
        style="max-width: 100%; height: auto"
      />
      <div v-if="fileSize">
        <p>文件大小: {{ fileSize }}</p>
        <a ref="downloadLink" :href="imageURL" :download="filename">下载图像</a>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      width: 5120,
      height: 5120,
      format: 'image/png',
      imageURL: null,
      loading: false,
      filename: 'generated-image.png',
      fileSize: null // 用于存储文件大小
    }
  },
  methods: {
    async generateImage() {
      this.loading = true
      this.imageURL = null
      this.fileSize = null

      // 创建一个 canvas 元素
      const canvas = document.createElement('canvas')
      canvas.width = this.width
      canvas.height = this.height

      // 获取 canvas 上下文
      const ctx = canvas.getContext('2d')

      // 填充 canvas，使用随机颜色
      const imageData = ctx.createImageData(this.width, this.height)
      const data = imageData.data

      // 用随机颜色填充数据
      for (let i = 0; i < data.length; i += 4) {
        data[i] = Math.random() * 255 // R
        data[i + 1] = Math.random() * 255 // G
        data[i + 2] = Math.random() * 255 // B
        data[i + 3] = 255 // A
      }

      ctx.putImageData(imageData, 0, 0)

      // 创建图片 Blob 对象
      canvas.toBlob((blob) => {
        if (blob) {
          const url = URL.createObjectURL(blob)
          this.imageURL = url
          this.fileSize = `${(blob.size / (1024 * 1024)).toFixed(2)} MB` // 文件大小，单位为 MB
          this.filename = `generated-image-${this.fileSize.split(' ')[0]}.png` // 设置文件名为文件大小
          this.loading = false
        }
      }, this.format)
    }
  }
}
</script>

<style scoped>
#app {
  text-align: center;
  padding: 20px;
}

button {
  margin: 20px;
  padding: 10px 20px;
  font-size: 16px;
}

img {
  margin-top: 20px;
  border: 1px solid #ddd;
}
</style>
